import React, {Component, Fragment, createRef} from 'react';
import io from 'socket.io-client'
import emitter from "../helper/ev" 
import Helper from '../helper/index'
import { Alert, Button, Row, Col, Input, Form} from 'antd'
import '../style/index.scss'

const {findIndex} = new Helper()

let socket 
const {TextArea, Search} = Input

class SocketIo extends Component{
    /**
     * 构造函数
     *
     * @param props 属性对象
     */
    constructor(props){
        super(props)
        this.state ={
            inputValue:'',
            list:[],
            username:'',
            userList:[]
        }
        this.chatBoxRef = createRef()
        this.sendChat = this.sendChat.bind(this)
    }

    /**
     * 组件挂载后执行的方法
     *
     * @description 在组件挂载后执行，用于处理WebSocket通信。
     *              连接WebSocket服务器，并监听进入、消息和离开事件。
     *              根据事件类型调用相应的方法处理用户进入、消息和离开的逻辑。
     *
     * @param {Object} props - 组件的props属性
     * @param {string} props.ws - WebSocket服务器的URL
     */
    componentDidMount(){
        const {ws} = this.props
        socket = io(ws)
        socket.on('enter', (data)=>{
            this.collectUsers(data.user)
            if(this.state.username===''){
                this.setState({
                    username:data.user
                })
            }
            this.rendChatList(data, 'enter')
        })

        socket.on('message', (data)=>{
            // console.log(data)
            this.foundUser(data.user)
            this.rendChatList(data, 'message')
        })

        socket.on('leave', (data)=>{
            this.removeUser(data.user)
            this.rendChatList(data, 'leave')
        })
    }

    /**
     * 将用户添加到用户列表中，并通知所有监听者
     *
     * @param {string} target 用户名称
     */
    collectUsers(target){
        let obj, index= this.state.userList.length
        // console.log(target)
        obj = {
            id:index,
            avatar:"https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png",
            username:target,
            url:"https://mfree.xyz",
            desc:`${target}  come in`
        }
        // console.log(obj)
        this.setState({
            userList:[...this.state.userList, obj]
        })
        emitter.emit("callMe", this.state.userList)
    }

    /**
     * 从用户列表中移除指定用户
     *
     * @param {string} target - 要移除的用户的用户名
     */
    removeUser(target){
        // console.log(target)
        let index = findIndex(this.state.userList, 'username', target)
        this.state.userList.splice(index, 1)
        emitter.emit("callMe", this.state.userList)
    }

    /**
     * 根据用户名查找用户
     *
     * @param {string} target 用户名
     */
    foundUser(target){
        console.log(target)
        let index = findIndex(this.state.userList, 'username', target)
        if(index===-1){
            this.collectUsers(target)
        }
    }

    sendChat = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
          if (!err) {
            socket.emit('message', values)
          }
        });
    };

    /**
     * 发送输入内容
     *
     * @param value 要发送的内容
     */
    sendInput(value){
        let obj ={
            chat:value
        }
        socket.emit('message', obj)
    }

    /**
     * 渲染聊天列表
     *
     * @param req 请求对象，包含用户信息和聊天信息
     * @param type 聊天类型，可以是 "enter"（进入房间）或 "leave"（离开房间）
     */
    rendChatList(req, type){
        let obj, index = this.state.list.length
        switch(type){
            case "enter":
                obj = {
                    id:index,
                    user:req.user,
                    txt:req.tag
                }
            break
            case "leave":
                obj = {
                    id:index,
                    user:req.user,
                    txt:req.tag
                }
            break
            default:
                obj = {
                    id:index,
                    user:req.user,
                    txt:req.data.chat
                }
            break
        }
        if(this.state.username!==obj.user){
            obj.type = 'info'
            obj.offset = 0
        } else {
            obj.type = 'success'
            obj.offset = 8
        }
        this.setState({
            list:[...this.state.list, obj]
        })
        const chat = this.chatBoxRef.current
        if(chat){
            chat.scroll(0, chat.scrollHeight) 
        }
    }

    /**
     * 渲染组件
     *
     * @returns 返回 JSX 元素
     */
    render(){
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span: 0 },
            },
            wrapperCol: {
              xs: { span: 12 },
              sm: { span: 24 },
            },
          };
         
        const tailFormItemLayout = {
            wrapperCol: {
              xs: {
                span: 12,
                offset: 0,
              },
              sm: {
                span: 4,
                offset: 20,
              },
            },
          };  

        return (
            <Fragment>
                <div className="chat-box" ref={this.chatBoxRef}>
                    <Row>
                        {this.state.list.map((item, index)=>{
                            return (
                                <Col span={16} offset={item.offset} key={index} className="animated fadeIn">
                                    <Alert
                                        message={item.user}
                                        description={item.txt}
                                        type={item.type}
                                    />
                                    <br/>
                                </Col>
                            )
                        })}
                    </Row>
                </div>
                <Row>
                    <Col md={{span:24}} xs={{span:0}}>
                        <Form  {...formItemLayout} onSubmit={this.sendChat}>
                            <Form.Item>
                            {getFieldDecorator('chat', {
                                    rules: [{ required: true, message: 'Please input your chat!' }],
                                })(
                                    <TextArea rows={5} placeholder="Please input your chat..." />,
                                )}
                            </Form.Item>
                            <Form.Item {...tailFormItemLayout}>
                                <Button type="primary" size={'large'} htmlType="submit" block><i className="fa fa-paper-plane-o"></i>&nbsp;&nbsp;&nbsp;发送</Button>
                            </Form.Item>
                        </Form>
                    </Col>
                    <Col md={{span:0}} xs={{span:24}}>
                        {/* <Form  {...formItemLayout} onSubmit={this.sendChat}>
                            <Form.Item>
                            {getFieldDecorator('chat', {
                                    rules: [{ required: true, message: 'Please input your chat!' }],
                                })(
                                    <TextArea rows={5} placeholder="Please input your chat..." />,
                                )}
                            </Form.Item>
                            <Form.Item {...tailFormItemLayout}>
                                <Button type="primary" size={'large'} htmlType="submit" block><i className="fa fa-paper-plane-o"></i>&nbsp;&nbsp;&nbsp;发送</Button>
                            </Form.Item>
                        </Form> */}
                        <Search
                            placeholder="input search text"
                            enterButton={<Button type="primary"><i className="fa fa-paper-plane-o"></i>&nbsp;&nbsp;&nbsp;发送</Button>}
                            size="large"
                            onSearch={this.sendInput}
                        />
                    </Col>
                </Row>
            </Fragment>
        )
    }
}

const WrappedSocketIo = Form.create({ name: 'socket_io' })(SocketIo);

export default WrappedSocketIo